package net.mtian.beijingnews.pager;

import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;

import net.mtian.beijingnews.activity.MainActivity;
import net.mtian.beijingnews.base.BasePager;
import net.mtian.beijingnews.base.MenuDetailBasePager;
import net.mtian.beijingnews.domain.NewsCenterPagerBean2;
import net.mtian.beijingnews.fragment.LeftMenuFragment;
import net.mtian.beijingnews.menudetailpager.InteracMenuDetailPager;
import net.mtian.beijingnews.menudetailpager.NewsMenuDetailPager;
import net.mtian.beijingnews.menudetailpager.PhotosMenuDetailPager;
import net.mtian.beijingnews.menudetailpager.TopicMenuDetailPager;
import net.mtian.beijingnews.utils.CacheUtils;
import net.mtian.beijingnews.utils.Contstants;
import net.mtian.beijingnews.utils.LogUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import static android.R.attr.data;

/**
 * 新闻中心
 * Created by mengm on 2017/1/2.
 */

public class NewsCenterPager extends BasePager {

    /**
     * 左侧菜单对应的数据
     */
    List<NewsCenterPagerBean2.DetailPagerData> data;

    public NewsCenterPager(Context context) {
        super(context);
    }

    private ArrayList<MenuDetailBasePager> detailBasePagers;

    @Override
    public void initData() {
        super.initData();
        ib_menu.setVisibility(View.VISIBLE);
        //1、设置标题
        tv_title.setText("新闻中心");
        //2、联网请求得到数据，创建视图
        TextView textView = new TextView(content);
        textView.setGravity(Gravity.CENTER);
        textView.setTextColor(Color.RED);
        textView.setTextSize(25);
        //3、把子视图添加到BasePager的FrameLayout中
        fl_content.addView(textView);
        //4、绑定数据
        textView.setText("新闻中心页面内容");

        //获取缓存数据
        String saveJson = CacheUtils.getString(content, Contstants.NEWSCENTER_PAGER_URL);
        if (!TextUtils.isEmpty(saveJson)){
            processData(saveJson);
        }

        //联网请求数据
        getDataFromNet();
    }

    /**
     * 使用xUtils请求数据
     */
    private void getDataFromNet() {
        //RequestParams params = new RequestParams(Contstants.NEWSCENTER_PAGER_URL);
        RequestParams params = new RequestParams("http://192.168.31.233/beijingnews/categories.json");
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogUtil.e("使用xUtils联网请求成功=="+ result);

                //缓存数据
                CacheUtils.putString(content, Contstants.NEWSCENTER_PAGER_URL, result);

                //解释json数据
                processData(result);

                //设置适配器
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                LogUtil.e("使用xUtils联网请求失败=="+ ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {
                LogUtil.e("使用xUtils联网请求成功==onCancelled");
            }

            @Override
            public void onFinished() {
                LogUtil.e("使用xUtils联网请求成功==onFinished");
            }
        });
    }

    /**
     * 解释json数据和显示数据
     * @param json
     */
    private void processData(String json) {
//        NewsCenterPagerBean bean = parsedJson(json);
        NewsCenterPagerBean2 bean2 = parsedJson2(json);

        String title2 = bean2.getData().get(0).getChildren().get(2).getTitle();
        LogUtil.e("解释成功222:::::" + title2);

//        String title = bean.getData().get(0).getChildren().get(1).getTitle();
//        LogUtil.e("解释成功:::::" + title);

        //给左侧菜单传递数据
        data = bean2.getData();

        MainActivity mainActivity = (MainActivity) content;
        LeftMenuFragment leftMenuFragment = mainActivity.getLeftMenuFragment();

        //添加详情页面
        detailBasePagers = new ArrayList<>();
        detailBasePagers.add(new NewsMenuDetailPager(content, data.get(0)));
        detailBasePagers.add(new TopicMenuDetailPager(content));
        detailBasePagers.add(new PhotosMenuDetailPager(content));
        detailBasePagers.add(new InteracMenuDetailPager(content));


        //把数据传递给左侧菜单
        leftMenuFragment.setData(data);
    }

    /**
     * 使用安卓系统自带的API解释json数据
     * @param json
     * @return
     */
    private NewsCenterPagerBean2 parsedJson2(String json) {

        NewsCenterPagerBean2 bean2 = new NewsCenterPagerBean2();
        try {
            JSONObject object = new JSONObject(json);

            int retcode = object.optInt("retcode");
            bean2.setRetcode(retcode);


            JSONArray data = object.optJSONArray("data");
            if (data != null && data.length() > 0){

                List<NewsCenterPagerBean2.DetailPagerData> detailPagerDatas = new ArrayList<>();
                bean2.setData(detailPagerDatas);

                for (int i = 0; i < data.length(); i++){
                    JSONObject jsonObject = (JSONObject) data.get(i);

                    NewsCenterPagerBean2.DetailPagerData detailPagerData = new NewsCenterPagerBean2.DetailPagerData();
                    detailPagerDatas.add(detailPagerData);

                    int id = jsonObject.optInt("id");
                    detailPagerData.setId(id);

                    int type = jsonObject.optInt("type");
                    detailPagerData.setType(type);

                    String title = jsonObject.optString("title");
                    detailPagerData.setTitle(title);

                    String url = jsonObject.optString("url");
                    detailPagerData.setUrl(url);

                    String url1 = jsonObject.optString("url1");
                    detailPagerData.setUrl1(url1);

                    String dayurl = jsonObject.optString("dayurl");
                    detailPagerData.setDayurl(dayurl);

                    String excurl = jsonObject.optString("excurl");
                    detailPagerData.setExcurl(excurl);

                    String weekurl = jsonObject.optString("weekurl");
                    detailPagerData.setWeekurl(weekurl);

                    JSONArray children = jsonObject.optJSONArray("children");
                    if (children != null && children.length() >0){
                        List<NewsCenterPagerBean2.DetailPagerData.ChildrenData> childrenDatas = new ArrayList<>();
                        detailPagerData.setChildren(childrenDatas);

                        for (int j = 0; j < children.length(); j++){
                            JSONObject childrenItem = (JSONObject) children.get(j);
                            NewsCenterPagerBean2.DetailPagerData.ChildrenData childrenData = new NewsCenterPagerBean2.DetailPagerData.ChildrenData();
                            childrenDatas.add(childrenData);

                            int childrenId = childrenItem.optInt("id");
                            childrenData.setId(childrenId);

                            int childrenType = childrenItem.optInt("type");
                            childrenData.setType(childrenType);

                            String childrenTitle = childrenItem.optString("title");
                            childrenData.setTitle(childrenTitle);

                            String childrenUrl = childrenItem.optString("url");
                            childrenData.setUrl(childrenUrl);
                        }
                    }
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return bean2;
    }

    /**
     * 解释json数据,使用系统的api解释json; 或使用Gson,fastjson
     * @param json
     * @return
     */
    private NewsCenterPagerBean2 parsedJson(String json) {
//        Gson gson = new Gson();
//        NewsCenterPagerBean bean = gson.fromJson(json, NewsCenterPagerBean.class);
        return new Gson().fromJson(json, NewsCenterPagerBean2.class);
    }

    /**
     * 根据position切换详情页面
     * @param position
     */
    public void switchPager(int position) {
        //1、切换标题
        tv_title.setText(data.get(position).getTitle());

        //2、移除之前的内容
        fl_content.removeAllViews();

        //3、添加新内容
        MenuDetailBasePager detailBasePager = detailBasePagers.get(position);
        View rootView = detailBasePager.rootView;
        detailBasePager.initData();//初始化数据
        fl_content.addView(rootView);

    }
}
